<template>
    <div class="container">
        <div class="left">
            <!-- <div class="left_top">
                      <vue-seamless-scroll :data="notices" :class-option="scrollClassOption">
                           <ul class="item">
                              <li v-for="item in notices" :key="item.id" style="cursor:pointer">
                                  <a :href="`/notices/preview/${item.id}`" target="_blank" >
                                  {{item.typeName}}</a>
                                  <a :href="`/notices/preview/${item.id}`" target="_blank">
                                  {{item.createTime}}</a>
                                  <a :href="`/notices/preview/${item.id}`" target="_blank"
                                  style="color: #dd6161">{{item.title}}</a>
                                  <a :href="`/notices/preview/${item.id}`" target="_blank"
                                  style="color: #dd6161">{{item.summary}}</a>
                              </li>
                          </ul>
                      </vue-seamless-scroll>
                  </div> -->
            <div class="login-bg">
                <img :src="loginLogoBackgroundUrl" alt="登录背景图" style="width: 536px; height: 536px" />
                <div style="
            position: absolute;
            top: 10px;
            left: 0;
            display: flex;
            align-items: center;
          ">
                    <img src="/images/linkHealthCareLogo.png" alt="" class="linkHealthCareLogo" />
                    <img :src="systemLogoUrl" class="system-logo" alt="系统LOGO" />
                </div>
            </div>
        </div>
        <div class="right">
            <div class="login-form">
                <div style="font-size: 26px; font-weight: blod; text-align: center">
                    上海市级医院<br />病理诊断系统
                </div>
                <div>
                    <el-input placeholder="请输入用户名" v-model="username">
                        <font-awesome-icon :icon="['fas', 'user']" slot="prepend">
                        </font-awesome-icon>
                    </el-input>
                </div>
                <div>
                    <el-input placeholder="请输入密码" type="password" @submit.native.prevent @keyup.13.native="userLogin"
                        v-model="password">
                        <font-awesome-icon :icon="['fas', 'lock']" slot="prepend">
                        </font-awesome-icon>
                    </el-input>
                </div>
                <!-- <div style="display:flex;">
                            <div style="border-bottom:1px solid #DCDFE6;margin-right:0;padding-top:10px;width: 13px;" class="el-input-group__prepend">
                              <img src="/images/hospital.png" alt="" style="width:18px;height:18px;"/>
                            </div>
                            <el-select placeholder="请选择机构" v-model="hospitalValue" style="margin-left: 0;margin-right: -5px;border-top-left-radius: 0;border-bottom-left-radius: 0;">
                                <el-option
                                  v-for="item in hospitalOptions"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value">
                                </el-option>
                            </el-select>
                        </div>
                        <div style="display:flex;">
                            <div style="border-bottom:1px solid #DCDFE6;margin-right:0;padding-top:10px;width: 13px;" class="el-input-group__prepend">
                              <font-awesome-icon :icon="['fas', 'globe']"></font-awesome-icon>
                            </div>
                            <el-select placeholder="请选择系统" v-model="systemValue" style="margin-left: 0;margin-right: -5px;border-top-left-radius: 0;border-bottom-left-radius: 0;">
                                <el-option
                                  v-for="item in systemOptions"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value">
                                </el-option>
                            </el-select>
                        </div> -->
                <div style="padding-left: 6px; margin-right: 0" v-show="passwordStrength == 'true'">
                    <input type="text" placeholder="请输入验证码" maxlength="4" class="yanzhengma_input"
                        v-model="picLyanzhengma" />
                    <input type="button" id="code" @click="createCode" class="verification1" v-model="checkCode" />
                </div>
                <div>
                    <el-button type="primary" @click="userLogin" style="border-radius: 25px">登 录
                    </el-button>
                </div>
                <div style="font-size: 14px; letter-spacing: 1px">
                    <div style="margin: 0; margin-left: 10px">
                        版权所有:上海市申康医院发展中心
                    </div>
                    <div style="margin: 0; margin-left: 10px">
                        技术支持:赵老师 18355363415
                    </div>
                    <!-- <el-button type="text" size="mini" @click="downloadDialog = true">
                                  推荐浏览器下载
                              </el-button>
                              <el-dialog :close-on-click-modal="false"
                                          :visible.sync="downloadDialog"
                                          title="推荐浏览器下载">
                                  <el-tabs type="border-card" stretch="true"
                                            style="width: 100%;" v-model="showSystem">
                                      <el-tab-pane style="margin-top: 4px;"
                                                    label="Windows版本" name="Windows">
                                          适用于 Windows 10/8.1/8/7 64 位
                                      </el-tab-pane>
                                      <el-tab-pane style="margin-top: 4px;"
                                                    label="Mac" name="Mac">
                                          适用于 Mac OS X 10.8 或更高版本
                                      </el-tab-pane>
                                      <el-tab-pane style="margin-top: 4px;"
                                                    label="Linux" name="Linux">
                                          适用于 Linux fedora 和 openSUSE 系统
                                      </el-tab-pane>
                                  </el-tabs>
                              </el-dialog> -->
                </div>
            </div>
        </div>
        <el-dialog :visible.sync="isResetVisible" :title="resetMessage" :close-on-click-modal="false"
            :modal-append-to-body="false" append-to-body width="40%">
            <el-form label-width="80px" :model="resetForm" :rules="resetRule" ref="resetForm">
                <el-row class="reset-row">
                    <el-col :span="24">
                        <el-form-item label="身份证号" prop="pCardId">
                            <el-input placeholder="身份证号后四位" v-model="resetForm.pCardId" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-button class="login-button longin-reset" @click="loginResetset" :loading="isResetLoading">
                            用户重置并登录
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash';
import moment from 'moment/moment';
import VueSeamlessScroll from 'vue-seamless-scroll';
import { isPromptLoginMessage } from '@/client/libs/util';

export default {
    name: 'Login',
    components: {
        VueSeamlessScroll,
    },
    data() {
        const checkNumber = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('身份证号不能为空'));
            }
            // const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
            // if (reg.test(value)) {
            //     return callback();
            // }
            return callback();
        };
        return {
            isResetVisible: false,
            resetForm: { pCardId: '' },
            resetRule: {
                pCardId: [ // 身份证号码
                    {
                        type: 'number',
                        validator: checkNumber,
                        message: `请输入身份证号后四位`,
                        trigger: 'blur'
                    }
                ],
            },
            isResetLoading: false,
            resetMessage: '帐号已经登录!请输入身份证号重置,若重置失败,请联系管理员!',
            picLyanzhengma: '',
            checkCode: '',
            ImageServiceURL: process.env.ImageServiceURL,
            systemLogoUrl: '/images/logo-now.png',
            platformName: '',
            passwordStrength: false,
            notices: [],
            scrollClassOption: {
                // 轮播鼠标控制停止
                hoverStop: true,
                // 轮播速度
                step: 0.4,
                // 开始无缝滚动最小数据长度
                limitMoveNum: 1,
                direction: 1, // 0 往下 1 往上 2向左 3向右
                switchDisabledClass: 'NO',
            },
            // 登录背景图
            loginLogoBackgroundUrl: '/images/login-bg.png',

            username: '',
            password: '',
            hospitalOptions: [
                {
                    value: '上海市皮肤病医院',
                    label: '上海市皮肤病医院',
                },
                {
                    value: '复旦大学附属华东医院',
                    label: '复旦大学附属华东医院',
                },
            ],
            hospitalValue: '',
            systemOptions: [
                {
                    value: '基于人工智能的病理诊断与报告系统',
                    label: '基于人工智能的病理诊断与报告系统',
                },
                {
                    value: '科研平台',
                    label: '科研平台',
                },
            ],
            systemValue: '',
            downloadDialog: false,
        };
    },
    created() {
        //进入页面刷新验证码
        this.createCode();
    },
    mounted() {
        if (this.isEworldSatus) {
            if (window.parent) {
                window.parent.postMessage({ message: { from: 'aikeji', operate: 'loginOut' } }, '*')
            }
        } else {
            this.getPlatform();
            this.$store.commit('stateInit');
            this.noticesRequest();
            let href = window.location.href;
            if (href.indexOf('?') != -1) {
                let userInfo = this.getUrlParams();
                console.log(userInfo[0].username);
                console.log(userInfo[1].password);
                this.AvoiduserLogin(userInfo[0].username, userInfo[1].password);
            }
        }
    },

    computed: {
        isEworldSatus() { //是否是内嵌明天医网
            return this.$store.state.isEworld;
        },
        showSystem() {
            const p = navigator.platform;
            if (p.indexOf('Win') === 0) {
                return 'Windows';
            }
            if (p.indexOf('Mac') === 0) {
                return 'Mac';
            }
            if (p === 'X11' || p.indexOf('Linux') === 0) {
                return 'Linux';
            }

            return 'Windows';
        },
    },

    methods: {
        // 图片验证码
        createCode() {
            let code = '';
            var codeLength = 4; //验证码的长度
            var random = new Array(
                0,
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9,
                'A',
                'B',
                'C',
                'D',
                'E',
                'F',
                'G',
                'H',
                'I',
                'J',
                'K',
                'L',
                'M',
                'N',
                'O',
                'P',
                'Q',
                'R',
                'S',
                'T',
                'U',
                'V',
                'W',
                'X',
                'Y',
                'Z'
            ); //随机数
            for (var i = 0; i < codeLength; i++) {
                //循环操作
                var index = Math.floor(Math.random() * 36); //取得随机数的索引（0~35）
                code += random[index]; //根据索引取得随机数加到code上
            }
            this.checkCode = code; //把code值赋给验证码
        },

        async getPlatform() {
            try {
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: 'GET',
                    url: '/PROXY-Remote/institutions/platform',
                })
                    .then((res) => {
                        // 请求失败
                        if (res.data.code !== 200) {
                            throw new Error(res.data);
                        }
                        // 请求成功
                        const result = res.data.data;
                        this.platformName = result.name;
                        this.systemLogoUrl = this.ImageServiceURL + result.logoUrl;
                        this.passwordStrength = result.passwordStrength;
                    });
            } catch (e) {
                // 跳出
            }
        },
        getUrlParams(name) {
            // 不传name返回所有值，否则返回对应值
            var url = window.location.search;
            if (url.indexOf('?') == 1) {
                return false;
            }
            url = url.substr(1);
            url = url.split('&');
            var name = name || '';
            var nameres;
            // 获取全部参数及其值
            for (var i = 0; i < url.length; i++) {
                var info = url[i].split('=');
                var obj = {};
                obj[info[0]] = decodeURI(info[1]);
                url[i] = obj;
            }
            // 如果传入一个参数名称，就匹配其值
            if (name) {
                for (var i = 0; i < url.length; i++) {
                    for (const key in url[i]) {
                        if (key == name) {
                            nameres = url[i][key];
                        }
                    }
                }
            } else {
                nameres = url;
            }
            // 返回结果
            return nameres;
        },
        // 识别关键字以 PROXY- 开头
        async noticesRequest() {
            try {
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: 'GET',
                    url: '/PROXY-Remote/notices/bare',
                })
                    .then((res) => {
                        // 请求失败
                        if (res.data.code !== 200) {
                            throw new Error(res.data);
                        }

                        // 请求成功
                        const result = res.data;
                        console.log('result', result);
                        // 查询结果数据
                        this.notices = [];
                        result.data.forEach((t) => {
                            const item = {
                                id: t.id,
                                typeName: t.typeName,
                                createTime: moment(t.createTime)
                                    .format('YYYY-MM-DD'),
                                title: t.title,
                                summary: t.summary,
                            };
                            this.notices.push(item);
                        });
                    });
            } catch (e) {
                // 跳出
            }
        },
        userLogin() {
            if (this.passwordStrength == 'true') {
                this.picLyanzhengma.toUpperCase();
                if (this.picLyanzhengma == '') {
                    this.$message.error({
                        message: '请输入验证码',
                        duration: 1600
                    });
                } else if (this.picLyanzhengma.toUpperCase() != this.checkCode) {
                    this.$message.error({
                        message: '验证码不正确',
                        duration: 1600
                    });
                    this.createCode();
                    this.picLyanzhengma = '';
                } else {
                    this.goLogin();
                }
            } else {
                this.goLogin();
            }
        },
        async goLogin() {
            try {
                let Base64 = require('js-base64').Base64;
                let _this = this;
                await this.$axios({
                    method: 'POST',
                    url: '/PROXY-Remote/login',
                    params: {
                        username: this.username,
                        password: Base64.encode(this.password),
                    },
                })
                    .then((res) => {
                        if (res.data.code === 510) {
                            this.$message({
                                duration: 1000,
                                offset: 100,
                                showClose: false,
                                message: '您是第一次登录，请初始化密码，正在为您跳转...',
                                type: 'warning',
                                onClose: () => {
                                    // 在这跳转
                                    this.$router.push({
                                        name: 'Password',
                                        query: { username: this.username }
                                    });
                                },
                            });
                            return false;
                        }
                        // 请求失败
                        if (res.data.code !== 200) {
                            if (res.data.code === 500 && !res.data.data) {
                                this.isResetVisible = true;
                                return;
                            }
                            const message = res.data.message
                            if (isPromptLoginMessage(message, 'LOGIN')) {
                                _this.$message.warning(message);
                            }
                            return;
                        }
                        if (res.data.code === 200) {
                            // 请求成功
                            const result = res.data.data;
                            const platform = {
                                name: '浦东医院病理平台',
                            };
                            const user = {
                                id: result.userInfo.id,
                                name: result.userInfo.name,
                                headImgUrl: result.userInfo.headUrl,
                            };
                            const permissionList = result['ui-item'];
                            // console.log('permissionList-before', permissionList);
                            for (let init = 0; init < permissionList.length; init++) {
                                for (
                                    let i = 0;
                                    i < permissionList[init].permissionList.length;
                                    i++
                                ) {
                                    const iconString = permissionList[init].permissionList[i].icon;
                                    const [prefix, icon] = _.split(iconString, ' ');
                                    permissionList[init].permissionList[i].prefix = prefix;
                                    permissionList[init].permissionList[i].icon = icon;
                                }
                            }
                            // console.log('permissionList-after', permissionList);
                            // 存储缓存数据
                            this.$store.commit('setPlatform', platform);
                            this.$store.commit('setUser', user);
                            this.$store.commit('setPermissionList', permissionList);
                            this.$store.commit('loginTimeFlash');
                            // 设置登陆后的跳转页
                            this.$store.commit('setPropertyGeneral', {
                                key: 'nowRoute',
                                value: permissionList[0].permissionList[0].route,
                            });

                            this.$router.push({
                                path: permissionList[0].permissionList[0].route,
                            });

                            this.$axios({
                                method: 'GET',
                                url: `/PROXY-Remote/institutions/${result.userInfo.institutionId}`,
                            })
                                .then((res2) => {
                                    if (res2 && res2.data.code === 200) {
                                        const info = res2.data.data;
                                        const institution = {
                                            id: info.id,
                                            isPlatform: info.isPlatform,
                                            name: info.name,
                                            isEnableTaskClaim: info.isEnableTaskClaim,
                                        };
                                        this.$store.commit('setInstitution', institution);
                                    }
                                });
                        }
                    });
            } catch (e) {
                if (isPromptLoginMessage(e.message, 'LOGIN')) {
                    this.$message.error(e.message);
                }
            }
        },
        async loginResetset() {
            let isValidate = false;
            this.$refs.resetForm.validate((valid) => {
                if (valid) {
                    isValidate = true;
                }
            });
            if (!isValidate) {
                return;
            }
            this.isResetLoading = true;
            await this.$axios({
                // 详见 axios 请求配置项
                method: 'GET',
                url: `/login/reset/token/card/id/${this.username}/${this.resetForm.pCardId}`,
            })
                .then((res) => {
                    this.resetCount += 1;
                    this.isResetVisible = false;
                    // 请求失败
                    if (res.data.code !== 200 || !res.data.data) {
                        const message = '重置登录失败，请联系管理员重置！！！'
                        if (isPromptLoginMessage(message, 'LOGIN')) {
                            this.$message.warning({ message });
                        }
                        return;
                    }
                    this.userLogin();
                });
            this.resetForm.pCardId = '';
            this.isResetLoading = false;
        },
        async AvoiduserLogin(name, pass) {
            // 使用 try catch模式
            try {
                let Base64 = require('js-base64').Base64;
                let _this = this;
                await this.$axios({
                    method: 'POST',
                    url: '/PROXY-Remote/login',
                    params: {
                        username: name,
                        password: Base64.encode(pass),
                    },
                })
                    .then((res) => {
                        // 请求失败
                        if (res.data.code !== 200) {
                            throw new Error(res.data);
                        }
                        // 请求成功
                        const result = res.data.data;

                        const platform = {
                            name: '浦东医院病理平台',
                        };
                        const user = {
                            id: result.userInfo.id,
                            name: result.userInfo.name,
                            headImgUrl: result.userInfo.headUrl,
                        };
                        const permissionList = result['ui-item'];
                        console.log('permissionList-before', permissionList);
                        for (let init = 0; init < permissionList.length; init++) {
                            for (
                                let i = 0;
                                i < permissionList[init].permissionList.length;
                                i++
                            ) {
                                const iconString = permissionList[init].permissionList[i].icon;
                                const [prefix, icon] = _.split(iconString, ' ');
                                permissionList[init].permissionList[i].prefix = prefix;
                                permissionList[init].permissionList[i].icon = icon;
                            }
                        }
                        console.log('permissionList-after', permissionList);
                        // 存储缓存数据
                        _this.$store.commit('setPlatform', platform);
                        _this.$store.commit('setUser', user);
                        _this.$store.commit('setPermissionList', permissionList);
                        _this.$store.commit('loginTimeFlash');
                        // 设置登陆后的跳转页
                        _this.$store.commit('setPropertyGeneral', {
                            key: 'nowRoute',
                            value: permissionList[0].permissionList[0].route,
                        });
                        setTimeout(function () {
                            _this.$router.push('/diagnosis/scan');
                        }, 0);
                        this.$axios({
                            method: 'GET',
                            url: `/PROXY-Remote/institutions/${result.userInfo.institutionId}`,
                        })
                            .then((res2) => {
                                console.log(res2);
                                if (res2 && res2.data.code === 200) {
                                    const info = res2.data.data;
                                    const institution = {
                                        id: info.id,
                                        isPlatform: info.isPlatform,
                                        name: info.name,
                                        isEnableTaskClaim: info.isEnableTaskClaim,
                                    };
                                    this.$store.commit('setInstitution', institution);
                                }
                            });
                    });
            } catch (e) {
                if (isPromptLoginMessage(e.message, 'LOGIN')) {
                    this.$message.error(e.message);
                }
            }
        },
    },
};
</script>

<style scoped>
.left {
    float: left;
    width: 50%;
}

.right {
    width: 50%;
    margin-left: 52%;
    height: 400px;
}

.left_top {
    width: 100%;
    margin-top: 10px;
    height: 100px;
    overflow: hidden;
    font-size: small;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.left_top a {
    color: #00be8b;
    text-decoration: blink;
    background: #ffffff;
}

.container {
    width: 1100px;
    padding-top: 100px;
    margin: 0 auto;
}

.login-bg {
    position: relative;
    margin-left: 10px;
    float: left;
}

.login-bg .linkHealthCareLogo {
    width: 180px;
}

.login-bg .system-logo {}

.login-form {
    width: 260px;
    padding: 16px;
    margin-top: 46px;
    background: #ffffff;
}

.login-form div {
    margin: 5px;
    border-bottom: #f4f4f4 1px;
}

.login-form button {
    width: 100%;
    margin: 10px;
}

.yanzhengma_input {
    width: 125px;
    height: 40px;
    font-size: 14px;
    box-sizing: border-box;
    padding-left: 15px;
    border-radius: 5px;
    border: 1px solid #c1c1c1;
    display: inline-block;
    vertical-align: middle;
}

.verification1 {
    width: 100px;
    height: 40px;
    font-size: 18px;
    letter-spacing: 3px;
    color: #10a1df;
    background: #f2f2f5;
    border-radius: 5px;
    border: 1px solid #c1c1c1;
    margin-left: 19px;
    display: inline-block;
    vertical-align: middle;
    cursor: pointer;
}

.login-button {
    background-color: #10A1DF;
    color: white;
    border: #10A1DF 1px;
}

.reset-row /deep/ .longin-reset {
    margin-top: 12px;
    border-radius: 15px;
    min-height: 38px;
    width: 100%;
    height: 38px;
}
</style>
